#include <stdlib.h>
#include "device.h"
#include "widget.h"
#include "menu.h"

extern UIState uistate;
extern unsigned int * mask_fb;
unsigned int* menu_fb[3];

SDL_Surface *gScreen0;
SDL_Surface *gScreen1;
SDL_Surface *gScreen[2];

int main(int argc, char *argv[])
{
  // Initialize SDL's subsystems - in this case, only video.
  if (SDL_Init(SDL_INIT_VIDEO) < 0)  {
     fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
     exit(1);
  }

  atexit(SDL_Quit);
    
  // Attempt to create a MAX_XxMAX_Y window with 32bit pixels.
  gScreen0 = SDL_SetVideoMode(MAX_X, MAX_Y, 32, SDL_SWSURFACE);
  gScreen1 = SDL_SetVideoMode(MAX_X, MAX_Y, 32, SDL_SWSURFACE);
  gScreen[0]  = gScreen0;
  gScreen[1]  = gScreen1;

  menu_fb[0] = (unsigned int *)gScreen0->pixels;
  menu_fb[1] = (unsigned int *)gScreen1->pixels;

  mask_fb    = menu_fb[0]; 
  // Enable keyboard repeat to make sliders more tolerable
  SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

  // If we fail, return error.
  if ((gScreen0 == NULL) || (gScreen1 == NULL))  {
     fprintf(stderr, "Unable to set up video: %s\n", SDL_GetError());
     exit(1);
  } 

  while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event))  {
        switch (event.type)  {
            case SDL_MOUSEMOTION:
              // update mouse position
              uistate.mousex = event.motion.x;
              uistate.mousey = event.motion.y;
              break;
            case SDL_MOUSEBUTTONDOWN:
              // update button down state if left-clicking
              if (event.button.button == 1)
                uistate.mousedown = 1;
              break;
            case SDL_MOUSEBUTTONUP:
              // update button down state if left-clicking
              if (event.button.button == 1)
                uistate.mousedown = 0;
              break;
            case SDL_KEYDOWN:
              uistate.keyentered = event.key.keysym.sym;
              uistate.keypressed = 1;
              break;            
            case SDL_QUIT:
              return 0;
        }
    }

    if(uistate.keypressed == 1) {
        uistate.redraw = 2; 
    }
    else {
        SDL_Delay(10);
        if(uistate.redraw == 0) mask_fb = menu_fb[(uistate.next_fb&0x1)]; 
        SDL_UpdateRect(gScreen[uistate.next_fb&0x1], 0, 0, MAX_X, MAX_Y);    // update the screen , don't take all the cpu time
    }
    
    render();
  } 
}
